/*
 * CadastraCliente.java
 *
 * Created on 06/06/2010, 23:05:21
 */

package imobiliaria.gui;

import imobiliaria.controladores.*;
import imobiliaria.entidades.*;
import imobiliaria.util.*;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.util.logging.Level; // Apagar
import java.util.logging.Logger;
import javax.swing.JOptionPane;
 

/**
 * Gui para Cadastramento de clientes
 * @author Thiago Ferreira
 */
public class CadastraFuncionario extends javax.swing.JFrame {
    private Sistema sis;
    private InterfaceOpFuncionario telaAntiga;

    /** Creates new form CadastraCliente */
    public CadastraFuncionario(InterfaceOpFuncionario telaAntiga) {
        sis = new Sistema();
        this.telaAntiga = telaAntiga;
        initComponents();
        setLocationRelativeTo(null);

        for (String ano : datasNascimentoValidas())
            JCB_Ano.addItem(ano);

        try {
            sis.atualizaDados();
        } catch (Exception e) {
            System.out.println("Erro: " + e.getMessage());
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        bGroupPreferencia = new javax.swing.ButtonGroup();
        JL_Nome = new javax.swing.JLabel();
        JL_Endereco = new javax.swing.JLabel();
        JL_Cpf = new javax.swing.JLabel();
        JL_Data = new javax.swing.JLabel();
        JTF_Nome = new javax.swing.JTextField();
        JTF_Cpf = new javax.swing.JTextField();
        JTF_Endereco = new javax.swing.JTextField();
        JL_Barra1 = new javax.swing.JLabel();
        JL_Barra2 = new javax.swing.JLabel();
        JL_TituloCC = new javax.swing.JLabel();
        JL_Info = new javax.swing.JLabel();
        JB_Cadastrar = new javax.swing.JButton();
        JB_Voltar = new javax.swing.JButton();
        JCB_Ano = new javax.swing.JComboBox();
        JCB_Mes = new javax.swing.JComboBox();
        JCB_Dia = new javax.swing.JComboBox();
        jLabel1 = new javax.swing.JLabel();
        JTF_Creci = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setTitle("iMobiliaria - Cadastramento de Cliente");
        setResizable(false);

        JL_Nome.setText("Nome:");

        JL_Endereco.setText("Endereço:");

        JL_Cpf.setText("CPF:");

        JL_Data.setText("Nascimento:");

        JTF_Nome.setToolTipText("Digite aqui seu nome");

        JTF_Cpf.setToolTipText("Digite seu cpf");

        JTF_Endereco.setToolTipText("Digite seu endereço");

        JL_Barra1.setText("/");

        JL_Barra2.setText("/");

        setLocationRelativeTo(null);
        JL_TituloCC.setFont(new java.awt.Font("DejaVu Sans", 1, 18));
        JL_TituloCC.setText("Cadastramento de Funcionario");

        JL_Info.setFont(new java.awt.Font("DejaVu Sans", 1, 13));
        JL_Info.setText("Preencha os dados abaixo, para cadastrar:");

        JB_Cadastrar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imobiliaria/images/okIcon.png"))); // NOI18N
        JB_Cadastrar.setText("Cadastrar-se");
        JB_Cadastrar.setToolTipText("Clique aqui para se cadastrar");
        JB_Cadastrar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_CadastrarActionPerformed(evt);
            }
        });

        JB_Voltar.setIcon(new javax.swing.ImageIcon(getClass().getResource("/imobiliaria/images/backIcon.png"))); // NOI18N
        JB_Voltar.setText("Voltar");
        JB_Voltar.setToolTipText("Clique aqui para voltar à tela de login");
        JB_Voltar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                JB_VoltarActionPerformed(evt);
            }
        });

        JCB_Ano.setMaximumRowCount(5);

        JCB_Mes.setMaximumRowCount(5);
        JCB_Mes.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Janeiro", "Fevereiro", "Março", "Abril", "Maio", "Junho", "Julho", "Agosto", "Setembro", "Outubro", "Novembro", "Dezembro" }));

        JCB_Dia.setMaximumRowCount(5);
        JCB_Dia.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", "23", "24", "25", "26", "27", "28", "29", "30", "31" }));

        jLabel1.setText("CRECI:");

        jLabel2.setText("(Digite apenas os números)");

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(172, 172, 172)
                .addComponent(JL_TituloCC, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                .addGap(155, 155, 155))
            .addGroup(layout.createSequentialGroup()
                .addGap(80, 80, 80)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addComponent(JL_Nome)
                    .addComponent(JL_Data)
                    .addComponent(JL_Endereco)
                    .addComponent(jLabel1)
                    .addComponent(JL_Cpf))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                        .addComponent(JTF_Endereco)
                        .addGroup(layout.createSequentialGroup()
                            .addComponent(JCB_Dia, javax.swing.GroupLayout.PREFERRED_SIZE, 64, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                            .addComponent(JL_Barra1, javax.swing.GroupLayout.PREFERRED_SIZE, 7, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(JCB_Mes, javax.swing.GroupLayout.PREFERRED_SIZE, 126, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                            .addComponent(JL_Barra2, javax.swing.GroupLayout.PREFERRED_SIZE, 14, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addGap(3, 3, 3)
                            .addComponent(JCB_Ano, javax.swing.GroupLayout.PREFERRED_SIZE, 83, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addComponent(JTF_Nome, javax.swing.GroupLayout.DEFAULT_SIZE, 344, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(JTF_Creci, javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(JTF_Cpf, javax.swing.GroupLayout.Alignment.LEADING, javax.swing.GroupLayout.DEFAULT_SIZE, 96, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jLabel2)))
                .addContainerGap(124, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(36, 36, 36)
                .addComponent(JL_Info)
                .addContainerGap(281, Short.MAX_VALUE))
            .addGroup(layout.createSequentialGroup()
                .addGap(201, 201, 201)
                .addComponent(JB_Cadastrar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(JB_Voltar)
                .addContainerGap(232, Short.MAX_VALUE))
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addGap(39, 39, 39)
                .addComponent(JL_TituloCC)
                .addGap(42, 42, 42)
                .addComponent(JL_Info)
                .addGap(45, 45, 45)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JTF_Nome, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_Nome))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JCB_Ano, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_Barra1)
                    .addComponent(JCB_Mes, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_Barra2)
                    .addComponent(JCB_Dia, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_Data))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JTF_Endereco, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(JL_Endereco))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JTF_Cpf)
                    .addComponent(jLabel2)
                    .addComponent(JL_Cpf))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JTF_Creci, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(jLabel1))
                .addGap(94, 94, 94)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(JB_Cadastrar)
                    .addComponent(JB_Voltar))
                .addContainerGap())
        );

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {JL_Barra1, JL_Barra2});

        layout.linkSize(javax.swing.SwingConstants.VERTICAL, new java.awt.Component[] {JB_Cadastrar, JB_Voltar});

        java.awt.Dimension screenSize = java.awt.Toolkit.getDefaultToolkit().getScreenSize();
        setBounds((screenSize.width-640)/2, (screenSize.height-480)/2, 640, 480);
    }// </editor-fold>//GEN-END:initComponents

    private void JB_VoltarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_VoltarActionPerformed
        dispose();
    }//GEN-LAST:event_JB_VoltarActionPerformed
 
    private void JB_CadastrarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_JB_CadastrarActionPerformed
        String cpf = JTF_Cpf.getText();
        String endereco = JTF_Endereco.getText();
        String nome = JTF_Nome.getText();

        String diaStr = JCB_Dia.getSelectedItem().toString();
        int mes = MetodoEntrada.recebeMesPeloNome(JCB_Mes.getSelectedItem().toString());
        String anoStr = JCB_Ano.getSelectedItem().toString();

        int dia = Integer.parseInt(diaStr);
        int ano = Integer.parseInt(anoStr);
        Calendar dataNascimento = new GregorianCalendar(ano,mes,dia);

        try {
            ControladorFuncionario.getInstance().adicionaFuncionario(cpf, dataNascimento, endereco, nome,
                    JTF_Creci.getText());
            Funcionario novoFunc = ControladorFuncionario.getInstance().
                    getFuncionarioPorCreci(JTF_Creci.getText());

            ControladorLogin.getInstance().adicionaLogin(novoFunc.getLogin());
            sis.salvarDados();

            JOptionPane.showMessageDialog(null, "Cadastro Efetuado com Sucesso!\n\n"
                  + "Dados de Entrada \n"
                  + "Login: " + novoFunc.getLogin().getUserName() + "\n" +
                  "Senha: " + novoFunc.getLogin().getSenha(),
                    "Cadastro Efetuado", JOptionPane.INFORMATION_MESSAGE);


            telaAntiga.atualizaFuncionarios();

            dispose();

        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, "Verifique se esses campos foram\n" +
                    "preenchidos corretamente:\n\n" +ex.getMessage(),
                    "Erro Ao Cadastrar", JOptionPane.ERROR_MESSAGE);
            Logger.getLogger(CadastraFuncionario.class.getName()).log(Level.SEVERE, null, ex);
        }
    }//GEN-LAST:event_JB_CadastrarActionPerformed

    /*
     * Metodo que retorna um array que ira ser adicionado no JComboBox,
     * de datas de nascimentos validas para seremcselecionadas pelo usuario,
     */
    private static String[] datasNascimentoValidas(){
        Calendar hoje = new GregorianCalendar();
        int MAIORDEIDADE = 18;
        int IDADELIMITE = 90;
        int primeiroAnoValido = hoje.get(Calendar.YEAR) - MAIORDEIDADE;
        int ultimoAnoValido = primeiroAnoValido - IDADELIMITE;
        int qtosAnosMostrar = primeiroAnoValido - ultimoAnoValido;
        String[] anosValidos = new String[qtosAnosMostrar];
        
        for(int i=0; i < qtosAnosMostrar;i++){
            int anoAdicionado = primeiroAnoValido - i;
            anosValidos[i] = Integer.toString(anoAdicionado);
        }
        return anosValidos;
    }
    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new CadastraFuncionario(new InterfaceOpFuncionario(
                        new InterfaceAdmin())).setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton JB_Cadastrar;
    private javax.swing.JButton JB_Voltar;
    private javax.swing.JComboBox JCB_Ano;
    private javax.swing.JComboBox JCB_Dia;
    private javax.swing.JComboBox JCB_Mes;
    private javax.swing.JLabel JL_Barra1;
    private javax.swing.JLabel JL_Barra2;
    private javax.swing.JLabel JL_Cpf;
    private javax.swing.JLabel JL_Data;
    private javax.swing.JLabel JL_Endereco;
    private javax.swing.JLabel JL_Info;
    private javax.swing.JLabel JL_Nome;
    private javax.swing.JLabel JL_TituloCC;
    private javax.swing.JTextField JTF_Cpf;
    private javax.swing.JTextField JTF_Creci;
    private javax.swing.JTextField JTF_Endereco;
    private javax.swing.JTextField JTF_Nome;
    private javax.swing.ButtonGroup bGroupPreferencia;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    // End of variables declaration//GEN-END:variables
    // Atributos
    
    /*private final String CADASTROEFETUADO = "Seu cadastro foi efetuado" +
    " com sucesso!\n\nLembre-se:\n" +
    "Seu login é seu cpf:\n" +
    "   Neste formato: 12345678910\n" +
    "Sua senha é sua data de nascimento\n" +
    "   Neste formato: 01011991\n\n" +
    "Você pode mudar seu login/senha quando desejar";*/
    // Fim de declaracao de atributos
}